<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <el-card>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <!-- <el-form-item label="品名">
          <el-input
            v-model="queryParams.wz"
            placeholder="请输入品名"
            clearable
            @keydown.enter.native.prevent="handleQuery"
          />
        </el-form-item> -->
        <el-form-item label="许可证号">
          <el-select
            v-model="queryParams.goodsPrice"
            placeholder="请选择许可证号"
            clearable
            filterable
          >
            <el-option
              v-for="item in licenseOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报关单号">
          <el-select
            v-model="queryParams.by7"
            placeholder="请选择报关单号"
            clearable
            filterable
          >
            <el-option
              v-for="item in customsOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="mt20">
      <el-table :data="inStockList" border stripe v-loading="loading">
        <el-table-column prop="entryTime" label="日期（按天计）">
          <template v-slot:default="{ row }">
            <div>{{ dayjs(row.entryTime).format("YYYY-MM-DD") }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="wz" label="品名">
          <template v-slot:default="{ row }">
            <el-button type="text" @click="openItemDetail(row)">{{ row.wz }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="jz" label="入库数量（KG）" />
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 品名详情弹窗 -->
    <el-dialog v-model="itemDialogVisible" :title="`品名详情 - ${currentItemName}`" width="80%">
      <el-table :data="itemDetailList" border stripe>
        <el-table-column prop="wz" label="品名" />
        <el-table-column prop="kw" label="库位" />
        <el-table-column prop="by8" label="料号" />
        <el-table-column prop="pz" label="皮重" />
        <el-table-column prop="mz" label="毛重" />
        <el-table-column prop="jz" label="净重" />
        <el-table-column prop="mzrq" label="毛重日期" width="170">
          <template v-slot:default="{ row }">
            <div>{{ dayjs(row.entryTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="pzrq" label="皮重日期" width="170">
          <template v-slot:default="{ row }">
            <div>{{ dayjs(row.entryTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="jzrq" label="净重日期" width="170">
          <template v-slot:default="{ row }">
            <div>{{ dayjs(row.entryTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="goodsPrice" label="许可证号" />
        <el-table-column prop="by7" label="报关单号" />
        <el-table-column prop="by13" label="运输工具号" />
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="itemDetailTotal"
          v-model:current-page="itemDetailQuery.pageNum"
          :page-size="itemDetailQuery.pageSize"
          @current-change="handleItemPageChange"
        />
      </div>

      <template #footer>
        <el-button @click="itemDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listReceiptOrder, itemStockInDetailList } from '@/api/wms/receiptOrder';
import { ref, reactive } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { queryLicenseList, queryCustomsNoList } from "@/api/wms/whole";

const loading = ref(false);
const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ch: '',
  wz: '',
  status: '',
  stockType: 'stockIn',
  by7: '',
  goodsPrice: '',
  pm: '高粱入库'
});

const inStockList = ref([]);

// 下拉选项
const licenseOptions = ref([]);
const customsOptions = ref([]);

function handleQuery() {
  loading.value = true;
  const query = { ...queryParams };
  listReceiptOrder(query)
    .then((response) => {
      inStockList.value = response.rows || [];
      total.value = response.total || 0;
    })
    .catch(() => {
      ElMessage.error('获取数据失败');
    })
    .finally(() => {
      loading.value = false;
    });
}

async function loadSelectOptions() {
  try {
    const [licenseRes, customsRes] = await Promise.all([
      queryLicenseList(),
      queryCustomsNoList(),
    ]);

    licenseOptions.value = (licenseRes.data || []).map((item) => {
      const num = parseFloat(item);
      return isNaN(num) ? item : Math.floor(num);
    });

    customsOptions.value = customsRes.data.filter((pre) => pre) || [];
  } catch (e) {
    ElMessage.error("加载下拉选项失败");
  }
}


function resetQuery() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    ch: '',
    wz: '',
    status: '',
    by7: '',
    goodsPrice: '',
    pm: '高粱入库'
  });
  handleQuery();
}

// 品名详情逻辑
const itemDialogVisible = ref(false);
const currentItemName = ref('');
const itemDetailList = ref([]);
const itemDetailTotal = ref(0);
const itemDetailQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  entryTime: ''
});

function openItemDetail(row) {
  currentItemName.value = row.wz;
  itemDetailQuery.entryTime = row.entryTime;
  itemDetailQuery.pageNum = 1;
  itemDialogVisible.value = true;
  fetchItemDetail();
}

function fetchItemDetail() {
  itemStockInDetailList({
    wz: currentItemName.value,
    pageNum: itemDetailQuery.pageNum,
    pageSize: itemDetailQuery.pageSize,
    stockType: 'stockIn',
    entryTime: itemDetailQuery.entryTime
  })
    .then((res) => {
      itemDetailList.value = res.rows || [];
      itemDetailTotal.value = res.total || 0;
    })
    .catch(() => {
      ElMessage.error('获取品名详情失败');
    });
}

function handleItemPageChange(page) {
  itemDetailQuery.pageNum = page;
  fetchItemDetail();
}

// 初始化
onMounted(() => {
  handleQuery();
  loadSelectOptions();
});
</script>

<style scoped>
.mt10 {
  margin-top: 10px;
}
.mt20 {
  margin-top: 20px;
}
.mb10 {
  margin-bottom: 10px;
}
.pagination-wrapper {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
